import {login, logout, getInfo} from '@/api/login'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const state = {
  token: getToken(),
  userinfo: null,
  roles: [],
  menus: [],
  permissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER: (state, userinfo) => {
    state.userinfo = userinfo
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

const actions = {
  // 用户登陆
  login({commit}, userInfo) {
    const {username, password, code, uuid} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password, code: code, uuid: uuid}).then(response => {
        console.log(response.data);
        commit('SET_TOKEN', response.data.Authorization);
        setToken(response.data.Authorization);
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取系统信息(路由，权限，角色等)
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        if (!response) {
          reject('getInfo: 登录验证失败，请重新登陆.')
        }
        const data = response.data
        if (!data) {
          reject('getInfo: userinfo must be a non-null object!')
        }
        const {roles, menus, permissions, userinfo} = data
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        if (!menus || menus.length <= 0) {
          reject('getInfo: menus must be a non-null array!')
        }

        commit('SET_USER', userinfo)
        commit('SET_ROLES', roles)
        commit('SET_MENUS', menus)
        commit('SET_PERMISSIONS', permissions)
        // resolve(response.result)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state, dispatch}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_USER', null)
        commit('SET_ROLES', [])
        commit('SET_MENUS', [])
        commit('SET_PERMISSIONS', [])
        removeToken()
        resetRouter()

        // 修复 登出时TagsView没有清除的 bug
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
